package com.jsgt.greekfire.ui.market

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.PopupWindow
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.viewpager.widget.ViewPager
import com.fhx.core.base.BaseActivity
import com.fhx.core.base.BaseFragment
import com.fhx.core.utils.ToastUtils
import com.github.fujianlian.klinechart.DataHelper
import com.github.fujianlian.klinechart.KLineChartAdapter
import com.github.fujianlian.klinechart.KLineEntity
import com.github.fujianlian.klinechart.draw.Status
import com.github.fujianlian.klinechart.formatter.DateFormatter
import com.github.fujianlian.klinechart.utils.ViewUtil
import com.google.android.material.tabs.TabLayout
import com.jsgt.greekfire.R
import com.jsgt.greekfire.dao.model.MarketBean
import com.jsgt.greekfire.factory.KLineViewModelFactory
import com.jsgt.greekfire.ui.market.fragement.DepthFragment
import com.jsgt.greekfire.ui.market.fragement.SynopsisFragment
import com.jsgt.greekfire.ui.market.fragement.VolumeFragment
import com.jsgt.greekfire.ui.trading.adapter.PagerAdapter
import com.jsgt.greekfire.viewmodel.KLineViewModel
import kotlinx.android.synthetic.main.activity_market_detail.title_layout
import kotlinx.android.synthetic.main.include_k_line_content.*
import kotlinx.android.synthetic.main.include_k_line_header.*
import kotlinx.android.synthetic.main.view_title.*
import org.jetbrains.anko.backgroundResource
import org.jetbrains.anko.imageResource
import org.jetbrains.anko.textColor
import org.jetbrains.anko.textColorResource
import java.text.DecimalFormat
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.*
import kotlin.collections.ArrayList
import kotlin.math.abs
import kotlin.math.min

/**
 * author fhx
 * create time 2020/4/27 10:25
 **/
class MarketDetailActivity : BaseActivity() {

    private val adapter by lazy { KLineChartAdapter() }
    private var typeString: String = ""
    private val titles by lazy { resources.getStringArray(R.array.k_line_tab) }
    private val granularities: IntArray =
        intArrayOf(60, 60, 300, 3600, 86400, 1800, 604800, 2592000)
    private val defaultCount = 5;

    //    private val cuntDownTime = 60000L //计时刷新数据的时间间隔
    private var isPopClick = false
    private var selectedTextView: TextView? = null
    private val defaultType = 2 //默认5分钟
    private var type = defaultType
    private val textViews: ArrayList<TextView>? = ArrayList()

    private var popupWindow: PopupWindow? = null
    private var moreTabLayout: LinearLayout? = null
    private var indexLayout: LinearLayout? = null

    private var depthFragment: DepthFragment? = null
    private var lastTime = 0L //深度最后刷新时间
    private val spacingTime = 300 //刷新间隔时间 - 毫秒
    private var volumeFragment: VolumeFragment? = null
    private var synopsisFragment: SynopsisFragment? = null
    private var lastTime1 = 0L //成交最后刷新时间

    private val fragments: MutableList<BaseFragment> = ArrayList()

    private val kLineViewModel: KLineViewModel by lazy {
        ViewModelProvider(
            this,
            KLineViewModelFactory()
        ).get(KLineViewModel::class.java)
    }


//    private val handler = @SuppressLint("HandlerLeak")
//    object : Handler() {
//        override fun handleMessage(msg: Message) {
//            when (msg.what) {
//                0 -> {
//                    getKLineData(granularities[type], false)
//                }
//            }
//        }
//    }
//
//    private val cuntDown = object : Runnable {
//        override fun run() {
//            if (!kLineChartView.isTouch) {
//                handler.sendEmptyMessage(0)
//            }
//            handler.postDelayed(this, cuntDownTime)
//        }
//    }

    companion object {
        private const val MARKET_BEAN = "bean"
        fun start(context: Context, marketBean: MarketBean) {
            val intent = Intent(context, MarketDetailActivity::class.java)
            intent.putExtra(MARKET_BEAN, marketBean)
            context.startActivity(intent)
        }
    }

    override fun getLayoutId(): Int = R.layout.activity_market_detail

    @SuppressLint("SetTextI18n", "ClickableViewAccessibility")
    override fun main() {
        title_layout.backgroundResource = R.color.pllo_161B2F
        back.imageResource = R.mipmap.ic_back1
        title_tv.textColorResource = R.color.white
        setStatusBar(R.color.pllo_161B2F, false, R.color.white)

        kLineChartView.adapter = adapter
        kLineChartView.dateTimeFormatter = DateFormatter()
        kLineChartView.setGridRows(4)
        kLineChartView.setGridColumns(4)
        kLineChartView.changeMainDrawType(Status.MA)
        kLineChartView.setChildDraw(0)

        // layout为与kChartView引起滑动冲突的view
        var xDown = 0.0f
        kLineChartView.setOnTouchListener { _, event ->
            if (event.pointerCount == 2) {
                appBarLayout.requestDisallowInterceptTouchEvent(true)
            } else if (event.action == MotionEvent.ACTION_DOWN) {
                xDown = event.x
            } else if (event.action == MotionEvent.ACTION_MOVE) {
                if (kLineChartView.isLongPress || abs(event.x - xDown) > 30) {
                    appBarLayout.requestDisallowInterceptTouchEvent(true)
                }

            } else if (event.action == MotionEvent.ACTION_UP || event.action == MotionEvent.ACTION_CANCEL) {
                appBarLayout.requestDisallowInterceptTouchEvent(false)
            }
            false
        }

        val marketBean = intent.getParcelableExtra<MarketBean>(MARKET_BEAN)
        typeString = marketBean?.symbol!!
        title = typeString.replace("_", "/").toUpperCase(Locale.getDefault())

        kDataOne.text = "$" + marketBean.last!!
        val df = DecimalFormat("######0.00")
        val df1 = DecimalFormat("######0.0000")
//        kDataText.text = "≈" + df.format(coinBean?.last?.times(7)) + "CNY"
        kDataText.text = marketBean.changePercentage.toString()
//        val upDown = coinBean.changepercentage!!.toString().substring(0,1);
        kRange.text = df.format(
            (marketBean.changePercentage!!.toString()
                .substring(1, marketBean.changePercentage.toString().length - 1)
                .toFloat() / 100 * marketBean.last!!)
        )
        if (marketBean.changePercentage!!.toString().startsWith("-")) {
            kDataText.textColor = ContextCompat.getColor(this, R.color.typeRed)
        } else {
            kDataText.textColor = ContextCompat.getColor(this, R.color.typeGreen)
        }

        kUp.text = df1.format(marketBean.dayHigh.toString().toDouble()).replace(".0000", "")
        kLow.text = df1.format(marketBean.dayLow.toString().toDouble()).replace(".0000", "")
        kCount.text = df1.format(marketBean.volume.toString().toDouble()).replace(".0000", "")

        initTextView(defaultCount)
        initPopWindow(defaultCount)
        tvMore.setOnClickListener {
            moreTabLayout!!.visibility = View.VISIBLE
            indexLayout!!.visibility = View.GONE
            showPopupWindow()
        }
        tvIndex.setOnClickListener {
            moreTabLayout!!.visibility = View.GONE
            indexLayout!!.visibility = View.VISIBLE
            showPopupWindow()
        }

        initDepthData()


        kLineViewModel.errorLiveData.observe(this, Observer {
            kLineChartView.refreshEnd()
//            handler.removeCallbacks(cuntDown)
        })
        kLineViewModel.kLineDataLiveData.observe(this, Observer {
            if (it == null || it.isEmpty()) {
                ToastUtils.show("未获取到数据")
            } else {
                val kLineEntityList = ArrayList<KLineEntity>();
                it.forEach { it1 ->
                    val entity = KLineEntity()
                    entity.Date = "00:00"
                    val dateFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.getDefault())
                    dateFormat.timeZone = TimeZone.getTimeZone("GMT")
                    try {
                        val dateTmp = dateFormat.parse(it1[0])
                        // Date还是按系统默认时区，而format格式化处来的字符串是GMT，所以要-8。
                        val dateFormat1 = if (granularities[type] >= 86400) {
                            SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
                        } else {
                            SimpleDateFormat("MM-dd HH:mm", Locale.getDefault())
                        }
                        dateFormat1.timeZone = TimeZone.getDefault()
                        val dateStrTmp: String = dateFormat1.format(dateTmp!!)
                        entity.Date = dateStrTmp
                    } catch (e: ParseException) {
                        e.printStackTrace()
                    }
                    entity.Open = it1[1].toFloat()
                    entity.High = it1[2].toFloat()
                    entity.Low = it1[3].toFloat()
                    entity.Close = it1[4].toFloat()
                    entity.Volume = it1[5].toFloat()
                    kLineEntityList.add(entity)
                }

                DataHelper.calculate(kLineEntityList)

                adapter.addFooterData(kLineEntityList)
                adapter.notifyDataSetChanged()
                kLineChartView.startAnimation()
                kLineChartView.refreshEnd()

//                handler.removeCallbacks(cuntDown)
//                handler.postDelayed(cuntDown, cuntDownTime)
            }
        })
        kLineViewModel.depthLiveData.observe(this, Observer {
            if (it?.asks == null || it.bids == null) {
                ToastUtils.show(getString(R.string.data_error))
            } else {
                it.asks = it.asks!!.subList(0, min(20, it.asks!!.size))
                it.bids = it.bids!!.subList(0, min(20, it.asks!!.size))
                depthFragment?.setData(it)
            }
        })
        kLineViewModel.dealsLiveData.observe(this, Observer {
            if (it == null) {
                ToastUtils.show(getString(R.string.data_error))
            } else {
                val it1 = it.reversed()
                volumeFragment?.setData(it1.subList(0, min(20, it.size)))
            }
        })
        kLineViewModel.currencyDescribeLiveData.observe(this, Observer {
            if (it == null) {
                ToastUtils.show(getString(R.string.data_error))
            } else {
                synopsisFragment?.setData(it)
            }
        })

        getKLineData(granularities[defaultType])
        kLineViewModel.getDepth(typeString)
        kLineViewModel.getDeals(typeString)
        kLineViewModel.getCurrencyDescribe(typeString.split("_")[0])
    }

    private fun getKLineData(granularity: Int) {
        getKLineData(granularity, true)
    }

    private fun getKLineData(granularity: Int, isShowLoading: Boolean) {
        if (isShowLoading) {
            kLineChartView.justShowLoading()
        }
        kLineViewModel.getKLineData(typeString, granularity)
    }

    private fun showPopupWindow() {
        if (popupWindow!!.isShowing) {
            popupWindow!!.dismiss()
        } else {
            popupWindow!!.showAsDropDown(llAllTab)
        }
    }

    /**
     * 初始化popwindow
     *
     * @param count
     */
    private fun initPopWindow(count: Int) {
        val contentView: View = LayoutInflater.from(this)
            .inflate(R.layout.layout_kline_popwindow, null)
        initPopChildView(contentView)
        intMoreTab(count)
        popupWindow = PopupWindow(this)
        popupWindow!!.contentView = contentView
        popupWindow!!.width = ViewGroup.LayoutParams.MATCH_PARENT
        popupWindow!!.height = ViewGroup.LayoutParams.WRAP_CONTENT
        popupWindow!!.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        popupWindow!!.isTouchable = true
        popupWindow!!.isFocusable = true
    }

    /**
     * 设置more显示内容
     *
     * @param count
     */
    private fun intMoreTab(count: Int) {
        val titles = listOf(*titles)
        for (i in count until titles.size) {
            val textView = LayoutInflater.from(this)
                .inflate(R.layout.textview_pop, null) as TextView
            val layoutParams =
                LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.WRAP_CONTENT,
                    LinearLayout.LayoutParams.MATCH_PARENT
                )
            textView.layoutParams = layoutParams
            textView.setPadding(ViewUtil.Dp2Px(this, 20.0f), 0, 0, 0)
            textView.text = titles[i]
            textView.tag = i
            textView.setOnClickListener { view ->
                isPopClick = true
                selectedTextView?.isSelected = false
                selectedTextView = view as TextView
                selectedTextView?.isSelected = true
                val selectedTag = selectedTextView!!.tag as Int
                type = selectedTag
                popupWindow!!.dismiss()
                getKLineData(granularities[type])
                kLineChartView.scrollTo(kLineChartView.maxScrollX, 0)
                if (type == 0) {
                    kLineChartView.setMainDrawLine(true)
                } else {
                    kLineChartView.setMainDrawLine(false)
                }

                tvMore.text = titles[type]
                tvMore.textColor =
                    ContextCompat.getColor(this@MarketDetailActivity, R.color.blue_main)
            }
            moreTabLayout!!.addView(textView)
            textViews?.add(textView)
        }
    }

    /**
     * 设置tab栏显示内容
     *
     * @param count
     */
    private fun initTextView(count: Int) {
        val titles = listOf<String>(*this.titles)
        for (i in titles.indices) {
            if (i < count) {
                val textView = LayoutInflater.from(this)
                    .inflate(R.layout.textview_pop, null) as TextView
                val layoutParams =
                    LinearLayout.LayoutParams(
                        ViewGroup.LayoutParams.WRAP_CONTENT,
                        ViewGroup.LayoutParams.MATCH_PARENT
                    )
                layoutParams.weight = 1f
                textView.layoutParams = layoutParams
                textView.text = titles[i]
                textView.tag = i
                if (i == defaultType) {
                    textView.isSelected = true
                    selectedTextView = textView
                }
                textView.setOnClickListener { view ->
                    isPopClick = false
                    selectedTextView?.isSelected = false
                    selectedTextView = view as TextView
                    selectedTextView?.isSelected = true
                    val selectedTag = selectedTextView!!.tag as Int
                    type = selectedTag
                    getKLineData(granularities[type])
                    if (type == 0) {
                        kLineChartView.setMainDrawLine(true)
                    } else {
                        kLineChartView.setMainDrawLine(false)
                    }

                    tvMore.text = resources.getString(R.string.more)
                    tvMore.textColor =
                        ContextCompat.getColor(this@MarketDetailActivity, R.color.primaryTextGray)
                }
                textViews?.add(textView)
                tab.addView(textView)
            }
        }
    }

    private var maView: TextView? = null
    private var bollView: TextView? = null
    private var macdView: TextView? = null
    private var kdjView: TextView? = null
    private var rsiView: TextView? = null
    private var hideChildView: TextView? = null
    private var hideMainView: TextView? = null

    /**
     * 初始化popwindow里的控件
     *
     * @param contentView
     */
    private fun initPopChildView(contentView: View) {
        val onClickListener: View.OnClickListener = View.OnClickListener {
            when (it.id) {
                R.id.tvMA -> {
                    maView!!.isSelected = true
                    bollView!!.isSelected = false
                    hideMainView!!.isSelected = false
                    kLineChartView.hideSelectData()
                    kLineChartView.changeMainDrawType(Status.MA)
                    popupWindow!!.dismiss()
                }

                R.id.tvBOLL -> {
                    maView!!.isSelected = false
                    bollView!!.isSelected = true
                    hideMainView!!.isSelected = false
                    kLineChartView.hideSelectData()
                    kLineChartView.changeMainDrawType(Status.BOLL)
                    popupWindow!!.dismiss()
                }

                R.id.tvMainHide -> {
                    maView!!.isSelected = false
                    bollView!!.isSelected = false
                    hideMainView!!.isSelected = true
                    kLineChartView.hideSelectData()
                    kLineChartView.changeMainDrawType(Status.NONE)
                    popupWindow!!.dismiss()
                }

                R.id.tvMACD -> {
                    macdView!!.isSelected = true
                    rsiView!!.isSelected = false
                    kdjView!!.isSelected = false
                    hideChildView!!.isSelected = false
                    kLineChartView.hideSelectData()
                    kLineChartView.setChildDraw(0)
                    popupWindow!!.dismiss()
                }

                R.id.tvKDJ -> {
                    macdView!!.isSelected = false
                    rsiView!!.isSelected = false
                    kdjView!!.isSelected = true
                    hideChildView!!.isSelected = false
                    kLineChartView.hideSelectData()
                    kLineChartView.setChildDraw(1)
                    popupWindow!!.dismiss()
                }

                R.id.tvRSI -> {
                    macdView!!.isSelected = false
                    rsiView!!.isSelected = true
                    kdjView!!.isSelected = false
                    hideChildView!!.isSelected = false
                    kLineChartView.hideSelectData()
                    kLineChartView.setChildDraw(2)
                    popupWindow!!.dismiss()
                }

                R.id.tvChildHide -> {
                    macdView!!.isSelected = false
                    rsiView!!.isSelected = false
                    kdjView!!.isSelected = false
                    hideChildView!!.isSelected = true
                    kLineChartView.hideSelectData()
                    kLineChartView.hideChildDraw()
                    popupWindow!!.dismiss()
                }
            }
        }

        moreTabLayout = contentView.findViewById(R.id.tabPop)
        indexLayout = contentView.findViewById(R.id.llIndex)
        maView = contentView.findViewById<TextView>(R.id.tvMA)
        maView?.setSelected(true)
        maView?.setOnClickListener(onClickListener)
        bollView = contentView.findViewById<TextView>(R.id.tvBOLL)
        bollView?.setOnClickListener(onClickListener)
        macdView = contentView.findViewById<TextView>(R.id.tvMACD)
        kdjView = contentView.findViewById<TextView>(R.id.tvKDJ)
        rsiView = contentView.findViewById<TextView>(R.id.tvRSI)
        hideMainView = contentView.findViewById<TextView>(R.id.tvMainHide)
        hideMainView?.setOnClickListener(onClickListener)
        macdView = contentView.findViewById<TextView>(R.id.tvMACD)
        macdView?.setSelected(true)
        macdView?.setOnClickListener(onClickListener)
        kdjView = contentView.findViewById<TextView>(R.id.tvKDJ)
        kdjView?.setOnClickListener(onClickListener)
        rsiView = contentView.findViewById<TextView>(R.id.tvRSI)
        rsiView?.setOnClickListener(onClickListener)
        hideChildView = contentView.findViewById<TextView>(R.id.tvChildHide)
        hideChildView?.setSelected(false)
        hideChildView?.setOnClickListener(onClickListener)
    }

    /**
     * 初始化深度图数据
     */
    private fun initDepthData() {
        depthFragment = DepthFragment.newInstance(typeString)
        volumeFragment = VolumeFragment.newInstance(typeString)
        synopsisFragment = SynopsisFragment.newInstance(typeString)
        fragments.add(depthFragment!!)
        fragments.add(volumeFragment!!)
        fragments.add(synopsisFragment!!)
        val tabArray =
            resources.getStringArray(R.array.k_line_depth)
        val tabs = java.util.ArrayList<String>()
        for (i in tabArray.indices) {
            tabs.add(tabArray[i])
        }

        vpDepth.adapter = PagerAdapter(
            supportFragmentManager,
            fragments,
            tabs
        )

        llDepthTab.tabMode = TabLayout.MODE_FIXED
        llDepthTab.setupWithViewPager(vpDepth)
        //        depthPager.setOffscreenPageLimit(fragments.size() - 1);
        vpDepth.currentItem = 0
        vpDepth.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrollStateChanged(state: Int) {
            }

            override fun onPageScrolled(
                position: Int,
                positionOffset: Float,
                positionOffsetPixels: Int
            ) {
            }

            override fun onPageSelected(position: Int) {
                if (position == 0) {
                    depthFragment?.refresh()
                } else if (position == 1) {
                    volumeFragment?.refresh()
                }
            }
        })
    }

    override fun onDestroy() {
//        handler.removeCallbacks(cuntDown)
        super.onDestroy()
    }
}